package msb.class04;


import org.junit.Assert;
import org.junit.Test;
import common.util.ArrayUtil;

/**
 * 使用递归获取最大值
 */
public class Code08_GetMax {


    public static int getMax(int[] arr) {
        return process(arr, 0, arr.length - 1);
    }

    /**
     * 数组  L..R 的最大值
     *
     * @param arr
     * @param L
     * @param R
     * @return
     */
    public static int process(int[] arr, int L, int R) {
        if (L == R) {
            return arr[L];
        }

        //获取L到R 的中点
        int mid = L + ((R - L) >> 1);
        int leftMax = process(arr, L, mid);
        int rightMax = process(arr, mid + 1, R);
        return Math.max(leftMax, rightMax);
    }

    @Test
    public void test() {
        for (int j = 0; j < 100; j++) {
            int[] instant = ArrayUtil.instant(100, 100);
            int actual = process(instant, 0, instant.length - 1);
            int expect = 0;
            for (int i = 0; i < instant.length; i++) {
                expect = Math.max(expect, instant[i]);
            }
            Assert.assertEquals(expect, actual);
        }
    }

}
